// ==UserScript==
// @name         沙雕知乎视频
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  try to take over the world!
// @author       Yours-bald-zhangsan
// @match        https://www.zhihu.com/
// @grant        unsafeWindow
// @run-at       document-start
// ==/UserScript==
;(function () {
  'use strict'
  const fetch = unsafeWindow.fetch
  const console = unsafeWindow.console
  const pluginName = '沙雕知乎视频'
  function log(...data) {
    console.log(pluginName, ...data)
  }
  // 需要屏蔽的关键词
  // const keyWords = ['家人们', '雄师少年', '刘暖曦', '刘鑫', '江歌', '陈世峰', '华晨宇', '分手']
  const keyWordsTitle = ['家人们', '雄师少年', '刘暖曦', '刘鑫', '江歌', '陈世峰', '华晨宇', '分手', '千万别再']
  const keyWordsContent = ['RNM']
  const oneDay = 24 * 60 * 60 * 1000
  const oneYear = 365 * oneDay
  const oneSeason = 90 * oneDay
  const now = Date.now()
  const colorForLongAgo = '#CC0000'
  const colorForNotTooLongAgo = '#CC00FF'
  const colorForNowadays = '#666'

  function $(selector, doc = document) {
    return doc.querySelectorAll(selector)
  }

  function shouldHideByKeywordsTitle(title) {
    return title && keyWordsTitle.some(item => title.includes(item))
  }

  function shouldHideByKeywordsContent(item) {
    let content = ''
    if (item.target.content) {
      content = item.target.content
    } else if (item.target.excerpt) {
      content = item.target.excerpt
    } else if (item.target.excerpt_new) {
      content = item.target.excerpt_new
    }
    return content && keyWordsContent.some(item => content.includes(item))
  }

  window.addEventListener('load', () => {
    $('.Card.TopstoryItem').forEach(item => {
      let title = $('.ContentItem-title', item)?.[0]?.innerText
      if (shouldHideByKeywordsTitle(title)) {
        item.remove()
        log('首页内容 关键字屏蔽', title)
      }
    })
  })

  // intercept fetch ， rewrite response.json for url recommend

  function addtoContent(item, content2beAdd) {
    if (item.target.content) {
      item.target.content = `${content2beAdd}${item.target.content}`
    }
    if (item.target.excerpt) {
      item.target.excerpt = `${content2beAdd}${item.target.excerpt}`
    }
    if (item.target.excerpt_new) {
      item.target.excerpt_new = `${content2beAdd}${item.target.excerpt_new}`
    }
  }

  function isAd(item) {
    return Boolean(item.ad)
  }

  function isVideo(item) {
    return Boolean(item.target?.thumbnail_extra_info?.video_id)
  }

  function isPaid(item) {
    return item.target?.answer_type == 'paid'
  }

  function filterData(data) {
    return data.filter(item => {
      // 从标题上屏蔽关键词
      let title = item.target?.question?.title
      if (isAd(item)) {
        return false
      }
      if (isVideo(item)) {
        return false
      }

      if (isPaid(item)) {
        log(`删除付费结果: ${title}`)
        return false
      }

      if (shouldHideByKeywordsTitle(title)) {
        log(`关键词屏蔽： ${title}`)
        return false
      }
      if (shouldHideByKeywordsContent(item)) {
        log(`内容关键词屏蔽： ${title}`)
        return false
      }
      return true
    })
  }

  function modifyDataAddDate(item) {
    // 开始改造内容
    let updateDate = item.target?.updated_time
    if (!updateDate) {
      updateDate = item.target?.updated
    }

    if (updateDate) {
      updateDate = updateDate * 1000
      let date = new Date(updateDate)
      let gap = now - updateDate
      let color = colorForNowadays
      if (gap > oneYear) {
        color = colorForLongAgo
      } else if (gap > oneSeason) {
        color = colorForNotTooLongAgo
      }
      let dateStr = `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`
      let dateTitleStr = `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()} ${date.getHours()}:${date.getMinutes()}`
      addtoContent(item, `<span style="color:${color}" title='${dateTitleStr}'>${dateStr}</span><br>`)
    } else {
      log(`这里有个数据找不到时间`, item)
    }
  }

  function modifyDataUnlikeItem(item) {
    let voteup_count = item.target?.voteup_count
    let comment_count = item.target?.comment_count
    // ['excerpt','excerpt_new']
    if (comment_count !== undefined && voteup_count !== undefined) {
      if (comment_count / voteup_count > 2) {
        item.target.content = item.target.excerpt = item.target.excerpt_new = '<span style="color:#999"> 这一条回答大概完全没有营养，别手贱点开了<span>'
        // log(item.target.excerpt)
        // log(item)
      }
    }
  }

  function modifyDataAddAnnoyTag(item) {
    if (item.target?.comment_permission == 'censor') {
      addtoContent(item, `<span style="color:#CC0000">这个家伙设置了评论筛选，可能不是什么好东西</span><br>`)
    }
  }

  function modifyData(data) {
    data.forEach(item => {
      modifyDataAddAnnoyTag(item)
      modifyDataAddDate(item)
      modifyDataUnlikeItem(item)
    })
  }

  function interceptResponse(response) {
    return response.json().then(body => {
      response.json = function wrappedJson() {
        try {
          let { data } = body
          const filteredData = filterData(data)
          if (filteredData.length == data.length) {
            log(`知乎转性了？ 居然没有视频，来，手动检查一下`)
            log(data)
          }

          modifyData(filteredData)

          body.data = filteredData
          return Promise.resolve(body)
        } catch (e) {
          console.error(`${pluginName} -- 解析数据出错了`, e)
          return Promise.resolve(body)
        }
      }
      return response
    })
  }

  function isRequestRecommend(response) {
    return response.url.includes('feed/topstory/recommend')
  }

  unsafeWindow.fetch = function wrappedFetch(...args) {
    return fetch(...args).then(response => {
      if (isRequestRecommend(response)) {
        return interceptResponse(response)
      }
      return response
    })
  }

  //document.addEventListener('DOMNodeInserted',debounce(start,200))
  function removeAd() {
    ;['.css-5tmz26', '.css-11h6utu'].forEach(cls => document.querySelector(cls)?.parentNode.remove())
  }
  //removeAd()
  function removeVideoCard() {
    ;['.VideoAnswerPlayer', '.ZVideoItem-player'].forEach(cls => {
      const nodes = document.querySelectorAll(cls)
      if (nodes.length > 0) {
        nodes.forEach(item => {
          let parent = item.parentNode
          while (parent && !parent.classList.contains('TopstoryItem-isRecommend')) {
            parent = parent.parentNode
          }
          if (parent) {
            parent.remove()
          }
        })
      }
    })
  }
  function remove() {
    removeVideoCard()
    removeAd()
    // console.log('done remove')
  }
  let handle = null
  function start() {
    handle = setInterval(() => {
      remove()
    }, 500)
  }
  function stop() {
    remove()
    clearInterval(handle)
    handle = null
  }
  //知乎 首页包含了视频和广告的数据， 需要等加载好之后来执行一下
  unsafeWindow.addEventListener('load', stop)
  document.addEventListener('DOMContentLoaded', start)
  //start()
})()
